<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Promise.any()</title>
</head>
<body>
    <h1>Promise.any()</h1>
    <h2>只要参数实例有一个变成fulfilled状态，包装实例就会变成fulfilled状态</h2>

    <script>
        // 基本用法
        const pErr = new Promise((resolve, reject) => {
            reject(new Error('失败'));
        });

        const pSlow = new Promise((resolve, reject) => {
            setTimeout(resolve, 500, '最终完成');
        });

        const pFast = new Promise((resolve, reject) => {
            setTimeout(resolve, 100, '很快完成');
        });

        Promise.any([pErr, pSlow, pFast])
            .then(value => {
                console.log(value); // '很快完成'
            });

        // 所有Promise都rejected的情况
        const rejected = Promise.any([
            Promise.reject('错误1'),
            Promise.reject('错误2'),
            Promise.reject('错误3')
        ]);

        rejected.catch(error => {
            console.log(error); // AggregateError: All promises were rejected
        });

        // 实际应用：从多个CDN加载资源
        function loadImage(url) {
            return new Promise((resolve, reject) => {
                const img = new Image();
                img.onload = () => resolve(url);
                img.onerror = () => reject(`Failed to load ${url}`);
                img.src = url;
            });
        }

        const CDNs = [
            'https://cdn1.example.com/image.jpg',
            'https://cdn2.example.com/image.jpg',
            'https://cdn3.example.com/image.jpg'
        ];

        Promise.any(CDNs.map(url => loadImage(url)))
            .then(firstSuccessfulUrl => {
                console.log('成功加载的URL:', firstSuccessfulUrl);
            })
            .catch(error => {
                console.log('所有CDN都加载失败');
            });
    </script>
</body>
</html> 